// pages/userinfo/index.js
import { Upload } from "../../model/Upload";
import { User } from "../../model/User.js";
const objUser = new User();
const upload = new Upload();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar: wx.getStorageSync('avatar'),
    nickName: wx.getStorageSync('nickName')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      avatar: wx.getStorageSync('avatar'),
      nickName: wx.getStorageSync('nickName')
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 修改头像
   */
  editAvater(){
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (result) => {
        let votes = this.data.voteItems;
        let tempFilePath = result.tempFilePaths[0];
        wx.showLoading({
          title: "上传中"
        });
        upload.upload([{
          url: tempFilePath
        }])
          .then(res => {
            wx.hideLoading();
            let file = JSON.parse(res[0]['data'])['data']['url'];
            this._setUserInfo({
              avatar:file
            });
          })
          .catch(err => {
            wx.showToast({
              title: err.msg,
              icon: "none"
            });
          });
      },
      fail: (err) => {
        if (err.errMsg === "chooseImage:fail cancel") {
          wx.showToast({
            title: '取消选择',
            icon: "none"
          })
        } else {
          wx.showToast({
            title: '微信接口调用失败',
            icon: "none"
          })
        }
      }
    });
  },
  /**
   * 提交用户信息
   */
  _setUserInfo(options){
    objUser.auth(options)
      .then(res => {
        if (res.flag == 1) {
          wx.showToast({
            title: '修改成功',
          })
          wx.setStorageSync("avatar", options.avatar);
          this.setData({
            avatar: options.avatar
          });
        }
      })
      .catch(err => {
        wx.showToast({
          title: err.msg,
          icon: "none"
        })
      });
  },
  /**
   * 修改昵称
   */
  gotoEditNickName(){
    wx.navigateTo({
      url: '/pages/editNickName/index',
    })
  }
})